package com.bt.lms.network.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bt.lms.constant.SysBizTypeConstant;
import com.bt.lms.entity.Role;
import com.bt.lms.entity.User;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.service.UserService;
import com.bt.lms.service.impl.UserServiceImpl;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户模块处理器接口实现
 *
 * @author 徐大永
 */
public class UserModuleHandler implements ModuleHandler {


    @Override
    public void handlerMsg(ReqMsg reqMsg, Socket socket) {

        //1.获取类型
        Short bizType = reqMsg.getBizType();
        //2.处理参数
        String data = reqMsg.getData();
        //3.调用业务接口(适配,得相应对象
        Object respObj = bizAdapter(bizType, data);
        //4.获取请求类型，是否需要响应
        Byte twoWay = reqMsg.getTwoWay();
        if (twoWay == ReqMsg.NETWORK_TWO_WAY_CHAT) {
            //双向，需要相应(还未获取状态，等后续)
            if (respObj != null) {
                //业务方法有返回值
                //响应
                RespMsg respMsg = objToRespMsg(reqMsg, respObj);
                byte[] bytes = respMsg.toBytes();
                try {
                    OutputStream out = socket.getOutputStream();
                    out.write(bytes);
                    out.flush();//冲刷
                    //关闭资源
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }

    /**
     * 响应对象转相应消息
     *
     * @param reqMsg  请求消息
     * @param respObj 响应对象
     * @return 相应消息
     */
    private RespMsg objToRespMsg(ReqMsg reqMsg, Object respObj) {

        //要返回的对象
        RespMsg respMsg = new RespMsg();

        //组装响应消息，1.消息头
        //魔数
        String magicNo = reqMsg.getMagicNo();
        respMsg.setMagicNo(magicNo);
        //协议版本号
        Byte version = reqMsg.getVersion();
        respMsg.setVersion(version);
        //序列化算法 serialCou
        Byte serialCou = reqMsg.getSerialCou();
        respMsg.setSerialCou(serialCou);
        //事件类型 evenType
        Byte evenType = reqMsg.getEvenType();
        respMsg.setEvenType(evenType);
        //业务类型 bizType
        Short bizTypeBytes = reqMsg.getBizType();
        respMsg.setBizType(bizTypeBytes);
        //请求id 毫秒数 reqId
        Long reqId = reqMsg.getReqId();
        respMsg.setReqId(reqId);
        //保留字段 remainField
        byte[] remainField = reqMsg.getRemainField();
        respMsg.setRemainField(remainField);
        //状态  status
        respMsg.setStatus(RespMsg.NETWORK_STATUS_NORMAL);
        //数据 data
        String data = JSON.toJSONString(respObj);
        respMsg.setData(data);

        return respMsg;
    }


    /**
     * 适配业务
     *
     * @param bizType 业务类型
     * @param data    数据
     * @return 响应对象
     */
    private Object bizAdapter(short bizType, String data) {
        //要返回的对象
        Object respObj = null;
        //业务对象
        UserService userService = new UserServiceImpl();

        //适配
        if (bizType == SysBizTypeConstant.USER_PAGE_QUERY) {

            Page<User> page = JSONObject.parseObject(data, Page.class);
            respObj = userService.queryPage(page,"");

//            List list = JSONObject.parseObject(data, List.class);
//            Page page = (Page)list.get(0);
//            String str = (String)list.get(1);
//            respObj = userService.queryPage(page, str);

        } else if (bizType == SysBizTypeConstant.USER_ADD) {

            User add = JSONObject.parseObject(data, User.class);
            respObj = userService.add(add);

        } else if (bizType == SysBizTypeConstant.USER_DELETE) {

            User del = JSONObject.parseObject(data, User.class);
            Long delId = del.getId();
            respObj = userService.del(delId);

        } else if (bizType == SysBizTypeConstant.USER_EDIT) {

            User edit = JSONObject.parseObject(data, User.class);
            respObj = userService.edit(edit);
        } else if (bizType == SysBizTypeConstant.USER_DETAILS) {

            User detail = JSONObject.parseObject(data, User.class);
            Long detailId = detail.getId();
            respObj = userService.detail(detailId);

        } else if (bizType == SysBizTypeConstant.USER_START) {

            User enable = JSONObject.parseObject(data, User.class);
            Long enableId = enable.getId();
            respObj = userService.enable(enableId);

        } else if (bizType == SysBizTypeConstant.USER_STOP) {

            User pause = JSONObject.parseObject(data, User.class);
            Long pauseId = pause.getId();
            respObj = userService.pause(pauseId);

        } else if (bizType == SysBizTypeConstant.USER_RESET_PWD) {

            User resetPsw = JSONObject.parseObject(data, User.class);
            Long resetPswId = resetPsw.getId();
            String resetPswPwd = resetPsw.getPassword();
            respObj = userService.resetPsw(resetPswId, resetPswPwd);

        } else if (bizType == SysBizTypeConstant.USER_ROLE_ADD_USER) {

            List idList = JSONObject.parseObject(data, List.class);
            List userIdList = JSONObject.parseObject(idList.get(0).toString(), List.class);
            List<Long> userIds = new ArrayList<>();
            for (Object obj:userIdList){
                Long userId = Long.parseLong(obj.toString());
                userIds.add(userId);
            }
            Long roleId = JSONObject.parseObject(idList.get(1).toString(), Long.class);
            respObj = userService.addRoleUser(userIds, roleId);//设置角色用户33

        } else if (bizType == SysBizTypeConstant.USER_ROLE_USER_DETAILS) {

            List list = JSONObject.parseObject(data, List.class);
            Page userPage = JSONObject.parseObject(list.get(0).toString(), Page.class);
            Integer roleIdInt = JSONObject.parseObject(list.get(1).toString(), Integer.class);
            Long roleId = roleIdInt.longValue();
            respObj = userService.queryUserFromRole(userPage, roleId);//查询角色用户
        }else if (bizType == SysBizTypeConstant.USER_ROLE_NOT_USER){

            List list = JSONObject.parseObject(data, List.class);
            Page userPage = JSONObject.parseObject(list.get(0).toString(), Page.class);
            Role role = JSONObject.parseObject(list.get(1).toString(), Role.class);
            Long roleId = role.getId();
            respObj = userService.queryRoleNotUser(userPage, roleId);//查询角色没有关联的用户

        }

        return respObj;
    }
}
